 <template>
	<div class="test-paper" v-loading.fullscreen.lock="loading"
		element-loading-text="拼命加载中">
        <el-row class="preview-head preview-head40" type="flex" align="middle">
            <el-col :span="2" :offset="1">
                <el-button type="text" @click="goBack()"><i class="el-icon-arrow-left"></i>返回</el-button>
            </el-col>
        </el-row>

		<div class="preview-conten maxW">
			
			<div class="preview-conten-l">
				
				<div class="preview-conten-l-h">
					<h3>{{testList.name}}</h3>
					<p>考试时间：{{testList.answer_time ? testList.answer_time : '--'}}分钟，满分{{totalScore}}分</p>
					<!-- <p>考试时间：100分钟，满分{{totalScore}}分</p> -->
				</div>

				<ul>
					<template v-for="type of testList.question_type" >
						<li class="preview-conten-list" :key="type.id">
							
							<!-- <div class="preview-conten-title" v-if="type.id == 1">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，只有一个符合题意的正确答案。错选，不选均不得分。)
							</div>

							<div class="preview-conten-title"  v-else-if="type.id == 2">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，有两个或两个以上符合题意的正确答案。多选、少选、错选、不选均不得分。)
							</div>

							<div class="preview-conten-title"  v-else-if="type.id == 9">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，两个答案中只有一个符合题意的正确答案。)
							</div>
							<div class="preview-conten-title"  v-else>
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，点击文本框，直接在文本框内作答即可。)
							</div> -->
							<div class="preview-conten-title" >
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，共{{type.score}}分<span v-show="type.common">，{{type.common}}。</span>)
							</div>

							<ul class="preview-conten-subject">

								<template v-for="(item, index) of testList.question_list" v-if="parseInt(item.qt_id) === parseInt(type.id)">
									<li class="preview-conten-subject-c"  v-if="parseInt(item.type_base_id) === 1 || parseInt(item.type_base_id) === 2 || parseInt(item.type_base_id) === 4">

										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{item.newInx}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{item.newInx}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
										</template>
										
										<ul class="preview-topic">

											<template v-for="(option,index2) of item.option" >

												<li class="preview-subject-title preview-false option-pattern" v-if="item.type_base_id === 4"  :key="index2">
													<template >
														<el-checkbox disabled :label="option.name"></el-checkbox>
													</template>
												</li>

												<template v-else>
													<li class="preview-subject-title preview-false" v-if="item.pattern === 1" :key="index2">
														<template>
															<el-checkbox disabled :label="option.name"></el-checkbox>
															<div  v-html="option.value"></div>
														</template>
													</li>

													<li class="preview-subject-title preview-false option-pattern" v-if="item.pattern === 2"  :key="index2">
														<template >
															<el-checkbox disabled :label="option.name"></el-checkbox>
															<!-- <div  v-html="option.value"></div> -->
														</template>
													</li>
												</template>
												
											</template>
											
										</ul>
											

										<el-collapse accordion class="preview-answer">
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>题型：{{item.question_type}}</span>
														<span>难度： {{item.difficulty}}</span>
														<span>重点程度： 高</span>
													</div>
												</template>
												<div class="preview-accordion-answer" >

													<span>正确答案： </span>
												
													<template >
														<div><i v-for="answer of item.answer">{{answer}}</i></div>
													</template>
													
												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>

									<li class="preview-conten-subject-c"  v-else>

										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{item.newInx}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{item.newInx}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
										</template>
										
										<ul class="preview-topic">
											<li class="preview-subject-title preview-false"  v-for="(option,index2) of item.option" :key="index2">
												<template>
													<el-checkbox disabled :label="option.name"></el-checkbox>
													<div  v-html="option.value"></div>
												</template>
											</li>
										</ul>
											

										<el-collapse accordion class="preview-answer">
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>题型：{{item.question_type}}</span>
														<span>难度： {{item.difficulty}}</span>
														<span v-if="item.keynote == 1">重点程度： 低</span>
														<span v-if="item.keynote == 2">重点程度： 中</span>
														<span v-if="item.keynote == 3">重点程度： 高</span>
													</div>
												</template>
											<!-- 	<div class="preview-accordion-answer">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div> -->
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>
								</template>

							</ul>
						</li>
					</template>
				</ul>
			</div>

			<div class="preview-conten-r test-paper-r">
				<template v-if="$route.query.authority == 1">
					<a :href="downloadFiler()">下载试卷</a>
					<el-button @click="newTestList()">添加到我的卷库</el-button>
					
				</template>
				
				<template v-else>
					<el-button @click="publishTest()">发布试卷</el-button>
					<a :href="downloadFiler()">下载试卷</a>
					<a @click.stop="setCopyTest()"  class="accordion-edit" >编辑</a>
					<el-button @click="copyTest()">复制试卷</el-button>
					<el-button @click="deldeteComment()">删除试卷</el-button>
				</template>
				
			</div>
		</div>

		<el-dialog
		  title="发布任务" width="550px"
		  :visible.sync="tasksVisible"
		  custom-class="Tailoring3" top="3vh"
		  :close-on-click-modal="false">
			  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm tasksVisible">

				  	<el-form-item label="任务名称" prop="name">
				  		<el-input v-model="ruleForm.name" placeholder="请输入任务名称，20个字符内" maxlength="20"></el-input>
				  	</el-form-item>

				  	<el-form-item label="任务对象" prop="obj">
				  		<el-checkbox-group v-model="ruleForm.obj">
				  			<template v-for="(item, index) of taskObject">
				  				<el-checkbox :label="item.id" name="type" :key="index">{{item.rename}}</el-checkbox>
				  			</template>
				  		</el-checkbox-group>
				  	</el-form-item>

				  	<el-form-item label="截止时间" prop="endTime">
				  		<!-- <el-time-picker placeholder="请选择时间" v-model="ruleForm.endTime"></el-time-picker> -->
				  		<el-date-picker
				  		     v-model="ruleForm.endTime" :picker-options='pickerOptions'
				  		     type="datetime"  value-format="yyyy-MM-dd HH:mm"
				  		     placeholder="请选择时间">
				  		   </el-date-picker>
				  	</el-form-item>

				  	<el-form-item label="任务时长" required class="task-duration">
				  			<el-form-item  prop="duration">
		        	            <el-input-number v-model="ruleForm.duration" controls-position="right" :step="1" step-strictly :min="0" :max="100" :disabled="unlimited" label="任务时长"></el-input-number>  分钟
				  			</el-form-item>

				  			<el-form-item  prop="unlimited">
				  				<el-checkbox v-model="ruleForm.unlimited" @change="unlimitedTime">不限时间</el-checkbox>
				  			</el-form-item>
				  	</el-form-item>

				  	<el-form-item label="任务描述" prop="content">
				  		<el-input type="textarea" v-model="ruleForm.content" :rows="4" maxlength="100" placeholder="100个字符内"></el-input>
				  		<span class="text-len"><i>{{ruleForm.content.length}}</i>/100</span>
				  	</el-form-item>

				  	<el-form-item label-width="0" class="task-content-btn">
				  		<el-button type="primary" @click="submitForm('ruleForm')">确认</el-button>
				  		<!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
				  	</el-form-item>

				</el-form>

		</el-dialog>

		<!-- 预览图片 -->
		<image-viewer 
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>
		
	</div>
</template>

<script>
	
	export default {
		data(){
			return {
				imgIndex: 0,
				imagePreview: {/*图片预览*/
					showViewer: false,
					previewSrcList: []
				},
				loading: true,
				pickerOptions: {
					disabledDate:(time) => {
						return time.getTime() < Date.now() - 8.64e7;
					}
				},
				tasksVisible: false,
				unlimited: false,
				headClassList: null,
				testList: [],/*试卷列表*/
				totalScore:0,/*试卷总分*/
				taskObject: [], /*任务对象数组*/
				ruleForm: {
					name: '',
					obj: [],
					endTime: '',
					duration: 100,
					unlimited: '',
					content: ''
				},
				rules: {
					name: [
						{ required: true, message: '请输入任务名称', trigger: 'blur' },
					],
					obj: [
						{ type: 'array', required: true, message: '请选择任务对象', trigger: 'change' },
					],
					endTime: [
						{ required: true, message: '请选择截止时间', trigger: 'change' },
					],
					duration: [
						{ required: true, message: '请输入任务时长', trigger: ['blur',  'change'] },
					],
					content: [
						// { required: true, message: '请输入任务描述', trigger: 'blur' },
					]
				}

			}
		},
		computed: {
			imageIndex() {
			    return this.imagePreview.previewSrcList.indexOf(this.imgIndex);
			}
		},
		mounted(){
			this.headClassList = document.querySelector('#trunk').classList;
			this.headClassList.add('hidden-header')

			document.querySelector('.preview-conten-l').addEventListener('click',  (e)=> {
				
				let [targetSrc ,imgs, srcArr, currentIdx] = ['', '', '', '']
				if (e.target.nodeName === 'IMG') {

					this.imagePreview.showViewer = true
					targetSrc = e.target.src;
					imgs = [...e.target.parentNode.children];
					srcArr = imgs.map(item=>item.currentSrc);
					currentIdx = srcArr.indexOf(targetSrc);

					this.imagePreview.previewSrcList = srcArr
					this.imgIndex = targetSrc

				}
			
			}, false)
		},
		destroyed(){
			this.headClassList.remove('hidden-header')
		},
		created(){
			this.getTestList()
		},
		methods: {
			/**
			 * 关闭图片
			 * @DateTime 2020-04-16T17:40:41+0800
			 * @qiu_m
			 * @return   {[type]}                 [description]
			 */
			 closeViewer() {
			 	this.imagePreview.showViewer = false;
			 	this.imagePreview.previewSrcList = []
			 },
			setCopyTest(obj){

				let success = (res)=>{
					// console.log(res.data)
					this.$router.push({path: '/test/knowledge-points', query: {edit: res.data, points: 1, copy: this.$route.query.id}})
				};
				let data = {id: this.$route.query.id}
				this.$ajax.post('api/newtest/copy_test', data, {func: {success: success}});
				// this.$ajax.post('api/newtest/copy_test', data, {func: {success:success}})
			},
			/**
			 * 不限时间
			 * @DateTime 2019-08-14T17:56:09+0800
			 * @return   {[type]}                 [description]
			 */
			unlimitedTime(val){

				if (val) {
					this.ruleForm.duration = 0
					this.unlimited = true
				}else{
					this.unlimited = false
					this.ruleForm.duration = 100
				}
			},
			/**
			 * 添加到我的卷库
			 * @DateTime 2019-08-14T16:46:32+0800
			 * @return   {[type]}                 [description]
			 */
			newTestList(){

				this.$confirm('是否复制改试卷到我的卷库？', '添加试卷', {
				    confirmButtonText: '确认',
				    cancelButtonText: '取消',
				    type: 'warning',
				    customClass: 'confirm-them',
				}).then(() => { 

					let id = ''
					let success = (res=>{
						this.$message.success(res.msg)
						id = res.data

						this.$confirm('该试卷已复制到我的卷库', '提示', {
						    confirmButtonText: '在我的卷库中编辑',
						    cancelButtonText: '好的',
						    type: 'warning',
						    customClass: 'confirm-them',
						}).then(() => { 

							this.$router.push({
								path: '/test/knowledge-points', 
								query: {edit: id, points: 1}
							})
						    	
						}).catch(() => {});

					});

					let params = {id: this.$route.query.id};

					this.$ajax.post('api/newtest/fav_test', params, {func: {success: success}})
				    
				}).catch(() => {});

				
			},
			/**
			 * 发布试卷
			 * @DateTime 2019-08-13T18:17:48+0800
			 * @return   {[type]}                 [description]
			 */
			publishTest(){
				if (this.$refs.ruleForm) {
					this.$refs.ruleForm.resetFields()
				}
				this.tasksVisible = true;
				this.getTaskObject()
			},
			/**
			 * 任务对象
			 * @DateTime 2019-08-13T18:14:23+0800
			 * @return   {[type]}                 [description]
			 */
			getTaskObject(){
				let success = (res=>{
					this.taskObject = res.data;
					console.log('taskObject',this.taskObject)
					this.ruleForm.duration = this.testList.answer_time != 0 ? this.testList.answer_time : 100
				});

				let params = {user_id: this.$g.user_id};

				this.$ajax({
					url: 'api/org/class_userid',
					method: 'get',
					params: params,
					func: {success: success}
				})
			},
			goBack(){

				if (this.$route.query.authority == 1) {
					this.$router.push({path: '/test/common-library'})
				}else if (this.$route.query.authority == 2) {
					this.$router.push({path: '/test/private-library'})
				}else{
					this.$router.back(-1)
				}
				
			},
			/**
			 * 根据参数请求试卷详情
			 * @DateTime 2019-07-22T17:37:30+0800
			 * @return   {[type]}                 [description]
			 */
			getTestList(){
				let success = (res=>{

				/*	this.$nextTick(()=>{
						//改变试题 img 的 url
						let imgArr = document.querySelectorAll('.preview-conten-subject-c img')
						let baseUrl = sessionStorage.getItem('host_addr');
						for (var i = 0; i < imgArr.length; i++) {
							let _temp = imgArr[i].src
							imgArr[i].src = _temp.replace(location.protocol+'//'+location.host, baseUrl);
						}
					});*/

					// this.testList.question_type.forEach( item =>{
					// 	this.totalScore += parseInt(item.score)
					// 	/*this.questionType.push({
					// 		id: item.id,
					// 		count: item.count,
					// 		name: item.question_type,
					// 		score: (parseInt(item.score)/parseInt(item.count))
					// 	})*/
					// });

					// 给所有问题添加一个题目的索引属性
					let data = res.data;
					let t = data.question_type;
					let q = data.question_list;
					let relInx = 0;
					for (let i = 0; i < t.length; i++) {
						const ti = t[i];
						this.totalScore += parseInt(ti.score)
						for (let j = 0; j < q.length; j++) {
							const qi = q[j];
							if(ti.id === qi.qt_id){
								relInx++;
								qi.newInx = relInx;
							}
						}
					}
					this.testList = data;
					this.loading = false;

				});

				let params = {
					user_id: this.$g.user_id,
					id: this.$route.query.id
				};

				this.$ajax({
					url: 'api/newtest/test_detail',
					method: 'get',
					params: params,
					func: {success: success}
				})
			},
			/**
			 * 下载试题
			 * @DateTime 2019-08-02T17:40:31+0800
			 * @return   {[type]}                 [description]
			 */
			downloadFiler(){
			
				return `${this.BASE_URL}/index/test/download_test?id=${this.$route.query.id}&answer=only_test`;
			},
			/**
			 * 发布任务表单
			 * @return {[type]} [description]
			 */
			 submitForm(formName) {

			 	this.$refs[formName].validate((valid) => {
			 		if (valid) {

			 			let endTime = (new Date(this.ruleForm.endTime)).getTime();
			 			let timestamp = (new Date()).getTime();

			 			if (endTime < timestamp) {
			 			    return this.$message.error('开始时间不能小于当前时间');
			 			}
			 			let unlimited = ''
			 			if (this.ruleForm.duration == 0) {
							unlimited = 1
			 			}else{
			 				unlimited = 0
			 			}
			 			
			 			let success = (res=>{
			 				this.$message.success(res.msg)
			 				this.tasksVisible = false

		 		
		 					this.ruleForm.name= ''
		 					this.ruleForm.obj = []
		 					this.ruleForm.endTime = ''
		 					this.ruleForm.duration = 100
		 					this.ruleForm.unlimited = ''
		 					this.ruleForm.content = ''
		 					this.unlimited = false
			 			});
// this.unlimited
			 			let params = {
			 				type: 2,
			 				resource_id: this.$route.query.id,
			 				name: this.ruleForm.name,
			 				end_time: this.ruleForm.endTime,
			 				length: this.ruleForm.duration,
			 				profile: this.ruleForm.content,
			 				class_id: this.ruleForm.obj.join(','),
			 				module: 'test',
			 				pattern: 1,
			 				is_unlimited:  unlimited/*1不限时  0限时*/
			 			};

			 			this.$ajax.post('api/task/add_issue_task', params, {func: {success: success}})
			 		} else {
			 			console.log('error submit!!');
			 			return false;
			 		}
			 	});
			 },
			/**
			 * 复制试卷
			 * @return {[type]} [description]
			 */
			copyTest(){
			    this.$confirm('确定要将该试卷复制一份到我的卷库吗？', '复制试卷', {
			        confirmButtonText: '确认',
			        cancelButtonText: '取消',
			        type: 'warning',
			        customClass: 'confirm-them',
			    }).then(() => {

			    	let success = (res=>{
			    		this.$message.success(res.msg)
			    	});
			    	let params = {id: this.$route.query.id};
			    	this.$ajax.post('api/newtest/fav_test', params, {func: {success: success}});
			        
			    }).catch(() => {});
			},
			/**
			 * 删除卷库
			 * @return {[type]} [description]
			 */
			deldeteComment(){
			    this.$confirm('确定要将该试卷从卷库中删除吗？', '提示', {
			        confirmButtonText: '确认',
			        cancelButtonText: '取消',
			        type: 'warning',
			        customClass: 'confirm-them',
			    }).then(() => {
			    	let success = ( res=>{
			    		this.$message.success(res.msg);
			    		this.$router.push('/test/private-library')
			    	});

			    	let params = {
			    		id: this.$route.query.id,
			    		status: 0
			    	};

			    	this.$ajax({
			    		url: 'api/newtest/save_test',
			    		method: 'put',
			    		data: params,
			    		func: {success: success}
			    	})

			    }).catch(() => {});
			},
		}
	}
</script>
